package cmd

import (
	"fmt"

	"downloader/internal/downloader"
	"downloader/internal/protocols"

	"github.com/spf13/cobra"
)

var downloadCmd = &cobra.Command{
	Use:   "download [url]",
	Short: "Download a file from the given URL",
	Args:  cobra.ExactArgs(1),
	RunE: func(cmd *cobra.Command, args []string) error {
		url := args[0]

		// Create downloader configuration
		config := &downloader.Config{
			MaxThreads: maxThreads,
			SpeedLimit: speedLimit,
			OutputDir:  outputDir,
			TempDir:    tempDir,
			ProxyURL:   proxyURL,
		}

		// Detect protocol and create appropriate downloader
		protocol := protocols.DetectProtocol(url)
		dl, err := downloader.New(protocol, config)
		if err != nil {
			return fmt.Errorf("failed to create downloader: %w", err)
		}

		// Start download
		fmt.Printf("Starting download from %s using %s protocol\n", url, protocol)
		if err := dl.Download(url); err != nil {
			return fmt.Errorf("download failed: %w", err)
		}

		fmt.Println("Download completed successfully")
		return nil
	},
}

func init() {
	// Add any download-specific flags here
	downloadCmd.Flags().BoolP("resume", "r", true, "enable resume support")
	downloadCmd.Flags().IntP("threads", "t", 5, "number of concurrent threads")
	downloadCmd.Flags().IntP("speed", "s", 0, "speed limit in bytes per second")
	downloadCmd.Flags().StringP("output", "o", "", "output directory")
	downloadCmd.Flags().StringP("tempoutput", "m", "", "temp directory")
	downloadCmd.Flags().StringP("proxy", "p", "", "proxy URL")
}

func Test(url string) error {
	outputDir := "./temp/"
	// Create downloader configuration
	config := &downloader.Config{
		MaxThreads: maxThreads,
		SpeedLimit: speedLimit,
		OutputDir:  outputDir,
		ProxyURL:   proxyURL,
	}

	// Detect protocol and create appropriate downloader
	protocol := protocols.DetectProtocol(url)
	dl, err := downloader.New(protocol, config)
	if err != nil {
		return fmt.Errorf("failed to create downloader: %w", err)
	}

	// Start download
	fmt.Printf("Starting download from %s using %s protocol\n", url, protocol)
	if err := dl.Download(url); err != nil {
		fmt.Println("Download failed:", err)
		return fmt.Errorf("download failed: %w", err)
	}

	fmt.Println("Download completed successfully")
	return nil
}
